package com.ma.a23.myjpa;

import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.jdbc.core.JdbcTemplate;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;

/**
 * @ClassName BaseDao
 * @Author: mayongqiang
 * @DATE 2022/4/13 15:18
 * @Description: 手写JPA
 */
public class BaseDao<T> {

    private static BasicDataSource dataSource = new BasicDataSource();

    // 设置数据库连接参数
    static {
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false");
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
    }



    private JdbcTemplate template = new JdbcTemplate(dataSource);

    private Class<T> beanClass;

    public BaseDao() {
        // 1、jdk拿到泛型参数
        beanClass = (Class) ((ParameterizedType)
                this.getClass().getGenericSuperclass())
                .getActualTypeArguments()[0];
        //2、spring 拿到泛型参数
        //beanClass = GenericTypeResolver.resolveTypeArgument(this.getClass(), BaseDao.class);
        //beanClass = ResolvableType.forClass(this.getClass()).getSuperType().getGeneric().resolve();

    }

    public void add(T bean) {

        Field[] declaredFields = beanClass.getDeclaredFields();
        String sql = "insert into "
                //+ beanClass.getSimpleName()
                + beanClass.getAnnotation(Table.class).value()
                + " values (";

        for (int i = 0; i < declaredFields.length; i++) {
            sql += "?";
            if (i < declaredFields.length - 1) {
                sql += ",";
            }
        }
        sql += ")";

        ArrayList<Object> paramsList = new ArrayList<>();
        for (Field declaredField : declaredFields) {
            try {
                declaredField.setAccessible(true);
                Object o = declaredField.get(bean);
                paramsList.add(o);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        int size = paramsList.size();
        Object[] params = paramsList.toArray(new Object[size]);


        int nums = template.update(sql, params);
        System.out.println(nums);


    }
}
